/**
 * Created by huangjun on 16-4-25.
 * 原生API
 */
import Vue from 'vue';
import resource from 'vue-resource';
Vue.use(resource);

define(function (require, exports, module) {
  /**
   * 1.代理请求
   */
  var requestCount = 0;

  function crm_ajax(option) {
    option.type = option.type || 'post';
    var param = option.param;
    var arr = [];
    var flag = option.url.indexOf('.json') == (option.url.length - 5);
    if (option.type.toLocaleString() == 'get') {
      if (param) {
        for (var key in param) {
          arr.push(key + '=' + param[key])
        }
        // if (arr.indexOf('isEncrypt=1') === -1) {
        //   arr.push('isEncrypt=1');
        // }
      } else {
        arr.push('isEncrypt=1');
      }
      param = arr.join('&');
      /* 转义 */
      if (param) {
        // if (os.ios) {
        //   param = encodeURI(encodeURI(param));
        // } else if (os.android) {
        //   param = encodeURI(param);
        // }
        if (option.url.indexOf('?') > -1) {
          option.url = option.url + '&' + param;
        } else {
          option.url = option.url + '?' + param;
        }
      }
      option.param = '';
    } else {
      if (param) {
        for (var key in param) {
          if (key == 'pageNo' || key == 'pageSize' || key == 'isEncrypt') {
            arr.push(key + '=' + param[key]);
          }
        }
        if (arr.length > 0) {
          param = arr.join('&');
          option.url = option.url + (param ? ('?' + param) : '');
        }
      }
    }
    if (!option.param) {
      option.param = '';
    }
    console.log('接口路径=' + option.url, '接口参数=' + JSON.stringify(option.param));
    // loading.show('loading...');
    requestCount++;
    var funcName = 'requestFinish' + requestCount;
    var errorName = 'requestFinishError' + requestCount;
    var postData = {
      'header': {
        'content-Type': 'application/json'
      },
      'reqURL': option.url,
      'reqType': option.type,
      'body': option.param,
      'datas': '',
      'sCallback': funcName,
      'fCallback': errorName
    };
    if (option.isEncode) {
      funcName += 'encode';
    }
    window[funcName] = function (retData) {
      setTimeout(function () {
        // loading.hide();
      }, 100);
      /* 请求成功 */
      if ('string' == typeof retData) {
        // if (!(os.ios || os.android)) {
        //   retData = JSON.parse(retData).data || {};
        // } else {
        //
        // }
        retData = JSON.parse(retData) || {};
        retData.codeNum = retData.code;
        retData.code = parseInt(retData.code);
        if (retData.isEncoded === 1) {
          console.log('=======base64=======');
          retData.data = JSON.parse(new Base64().decode(retData.data) || '{}');
        }
      }
      option.callback(retData);
    };
    window[errorName] = function (retData) {
      /* 请求失败 */
      setTimeout(function () {
        loading.hide();
      }, 100);
      if (typeof retData == 'string') {
        retData = JSON.parse(retData);
      }
      option.callback(retData);
    };
    postData.nativeDecode = 1;
    Vue.http({
      headers: {},
      url: option.url,
      method: option.type,
      emulateJSON: option.emulateJSON || true,
      data: JSON.stringify(option.param)
      /* body */
    }).then(function (retData) {
      if (typeof retData == 'object') {
        retData = JSON.stringify(retData)
      }
      window[funcName](retData);
    }, function (retData) {
      window[errorName](retData);
    });
  }

  /**
   * 3.拍照
   * 参数 json
   * 'apiJson': {
   *    'backType': '2', //1.表示只返回压缩图（不存本地）;2.表示只返回拍照生成的原图图片路径;3.表示返回压缩图和原图图片路径
   *    'wDivisor': '1024', //宽方向压缩的像素值
   *    'hDivisor': '780', //高方向压缩的像素值
   *    'uploadUrl': APIS.upload_file  //上传接口
   * }.
   * 'callback': function () {}
   * result: {'fId':'上传后附件ID', 'path':'上传后附件路径'}
   */
  function crm_goPhoto(param) {
    window['photoFinish'] = function (result) {
      if (typeof result == 'string') {
        result = JSON.parse(result);
      }
      if (result.isUpload) {
        loading.show('正在上传...');
        return;
      }
      loading.hide();
      if (result.status == 'cancel') {
        window['photoFinish'] = null;
        return;
      }
      if (result.status == 1 || (result.code != 200 && param.apiJson.uploadUrl)) {
        mui.alert(result.msg || '上传失败，请重试！', '提示', function () {
        });
        window['photoFinish'] = null;
        return;
      }
      if (!result.fileUrl && (os.ios || os.android)) {
        window['photoFinish'] = null;
        return;
      }
      param.callback(result);
      window['photoFinish'] = null;
    };
    var jsonParam = param.apiJson || {};
    jsonParam.sCallback = 'photoFinish';
    jsonParam.fCallback = 'photoFinish';
    jsonParam = JSON.stringify(jsonParam);
    if (os.ios) {
      var src = 'goPhoto(' + jsonParam + ')';
      var iframe = document.createElement('iframe');
      iframe.setAttribute('src', src);
      iframe.setAttribute('style', 'display:none;');
      document.body.appendChild(iframe);
      setTimeout(function () {
        document.body.removeChild(iframe);
      }, 200);
    } else if (os.android) {
      capturefunc.goPhoto(jsonParam);
    } else {
      uploadFilePC({
        'url': JSON.parse(jsonParam).uploadUrl,
        onSend: function () {
          window['photoFinish']({
            'isUpload': true
          });
        },
        success: function (retData) {
          loading.hide();
          if ('string' == typeof retData) {
            retData = JSON.parse(retData);
          }
          window['photoFinish'](retData);
        },
        error: function () {
          loading.hide();
          mui.alert('上传失败！', '提示', function () {
          });
        }
      });
    }
  }

  /**
   * 4.相册
   * 参数 json
   * 'apiJson': {
   *    'backType': '2', //1.表示只返回压缩图（不存本地）;2.表示只返回拍照生成的原图图片路径;3.表示返回压缩图和原图图片路径
   *    'wDivisor': '1024', //宽方向压缩的像素值
   *    'hDivisor': '780', //高方向压缩的像素值
   *    'uploadUrl': APIS.upload_file  //上传接口
   * }.
   * 'callback': function () {}
   * result: {'fId':'上传后附件ID', 'path':'上传后附件路径'}
   */
  function crm_fromImgLibrary(param) {
    window['photoFinish'] = function (result) {
      if (typeof result == 'string') {
        result = JSON.parse(result);
      }
      if (result.isUpload) {
        loading.show('正在上传...');
        return;
      }
      loading.hide();
      if (result.status == 'cancel') {
        window['photoFinish'] = null;
        return;
      }
      if (result.status == 1 || (result.code != 200 && param.apiJson.uploadUrl)) {
        mui.alert(result.msg || '上传失败，请重试！', '提示', function () {
        });
        window['photoFinish'] = null;
        return;
      }
      if (!result.fileUrl && (os.ios || os.android)) {
        window['photoFinish'] = null;
        return;
      }
      param.callback(result);
      window['photoFinish'] = null;
    };
    var jsonParam = param.apiJson || {};
    jsonParam.sCallback = 'photoFinish';
    jsonParam.fCallback = 'photoFinish';
    jsonParam = JSON.stringify(jsonParam);
    if (os.ios) {
      var src = 'fromImgLibrary(' + jsonParam + ')';
      var iframe = document.createElement('iframe');
      iframe.setAttribute('src', src);
      iframe.setAttribute('style', 'display:none;');
      document.body.appendChild(iframe);
      setTimeout(function () {
        document.body.removeChild(iframe);
      }, 200);
    } else if (os.android) {
      capturefunc.fromImgLibrary(jsonParam);
    } else {
      uploadFilePC({
        'url': JSON.parse(jsonParam).uploadUrl,
        onSend: function () {
          window['photoFinish']({
            'isUpload': true
          });
        },
        success: function (retData) {
          loading.hide();
          if ('string' == typeof retData) {
            retData = JSON.parse(retData);
          }
          window['photoFinish'](retData);
        },
        error: function () {
          loading.hide();
          mui.alert('上传失败！', '提示', function () {
          });
        }
      });
    }
  }

  /**
   * 15.返回前一个webView
   * 参数 json/null
   * 'apiJson': {
   *    'fn': '', //当前功能标示
   *    'callFun': '', //返回到上一个webView时,需要调用的function的名称, 注:安卓需要配合goView中的参数isTrue=true才能实现
   *    'param': {} //上一个参数的参数
   * }
   * result null
   */
  function crm_goNative(param) {
    param = param || {};
    var jsonParam = param.apiJson;
    jsonParam = jsonParam ? JSON.stringify(jsonParam) : '';
    jsonParam = JSON.parse(jsonParam || '{}');
    if (jsonParam.callFun && typeof window.parent[jsonParam.callFun] === 'function') {
      window.parent[jsonParam.callFun](jsonParam.param);
    }
    window.parent.closeIframe(jsonParam.fn);
  }

  /**
   * 16.附件上传
   * PC 模拟附件上传
   */
  var frameCount = 0;

  function uploadFilePC(potions) {
    document.querySelector('#uploadPc') && document.querySelector('#uploadPc').remove();
    var frag = document.createDocumentFragment();
    var $form = document.createElement('form');
    $form.setAttribute('id', 'uploadPc');
    $form.setAttribute('action', potions.url);
    $form.setAttribute('method', 'post');
    $form.setAttribute('enctype', 'multipart/form-data');
    $form.style.display = 'none';
    var $input = document.createElement('input');
    $input.setAttribute('id', 'uploadFiles');
    $input.setAttribute('name', 'file');
    $input.setAttribute('type', 'file');
    $form.appendChild($input);
    frag.appendChild($form);
    document.body.appendChild(frag);
    $input.addEventListener('change', function () {
      fileUpload();
    });
    setTimeout(function () {
      $input.click();
    }, 10)
    return;

    function fileUpload() {
      var fileValue = $input.value;
      // var imgExt = fileValue.substring(fileValue.lastIndexOf('.'), fileValue.length);
      var imgSize = document.getElementById('uploadFiles').files[0].size / 1024;
      if (!fileValue) {
        return;
      }
      /* if ('.jpg|.jpeg|.gif|.bmp|.png|'.indexOf(imgExt.toLocaleLowerCase() + '|') == -1) {
       mui.alert('上传图片格式不正确，请重新上传！', '提示', function(){});
       return;
       }*/
      if (!(imgSize > 0 && imgSize <= 2048)) {
        potions.error();
        return;
      }
      var form = $form;
      var id = 'jqFormIO' + frameCount++;
      var $io = document.createElement('iframe');
      $io.setAttribute('id', id);
      $io.setAttribute('name', id);
      $io.style.position = 'absolute';
      $io.style.top = '-1000px';
      $io.style.left = '-1000px';
      var io = $io;
      setTimeout(function () {
        document.body.appendChild($io);
        $io.attachEvent ? $io.attachEvent('onload', cb) : $io.addEventListener('load', cb, false);
        // var encAttr = form.encoding ? 'encoding' : 'enctype';
        var t = $form.getAttribute('target');
        $form.setAttribute('target', id);
        $form.setAttribute('method', 'POST');
        $form.setAttribute('encAttr', 'multipart/form-data');
        $form.setAttribute('action', potions.url);
        potions.onSend();
        form.submit();
        $form.setAttribute('target', t); // reset target
      }, 10);

      function cb() {
        io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
        var ok = true;
        try {
          var data, doc;
          doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
          data = doc.body ? doc.body.innerText : null;
          if (potions.dataType === 'json') {
            data = JSON.parse(data) || {};
          }
        } catch (e) {
          ok = false;
        }

        if (ok) {
          if (data) {
            console.log('===上次结果===' + data);
            var obj = {
              fid: 1234,
              url: '我的资料',
              name: '我的资料',
              type: 'doc',
              status: 2,
              code: 200
            };
            // potions.success(obj);
            potions.success(data);
          } else {
            potions.error();
          }
        } else {
          potions.error();
        }
        setTimeout(function () {
          $io.remove();
          $form.remove();
        }, 100);
      }
    }
  }

  /**
   * 附件上传
   * 参数 json
   */
  function crm_openAddFile(param) {
    window['uploadFinish'] = function (result) {
      if (typeof result == 'string') {
        result = JSON.parse(result);
      }
      console.info(JSON.stringify(result) + '打印附件');
      if (result.isUpload) {
        loading.show('正在上传...');
        return;
      }
      loading.hide();
      if (result.status == 'cancel') {
        window['uploadFinish'] = null;
        return;
      }
      if (result.status == 1 || (result.code != 200 && param.apiJson.uploadUrl)) {
        mui.alert(result.msg || '上传失败，请重试！', '提示', function () {
        });
        window['uploadFinish'] = null;
        return;
      }
      if (!result.fileUrl && (os.ios || os.android)) {
        window['uploadFinish'] = null;
        return;
      }
      param.callback(result);
      window['uploadFinish'] = null;
    };
    var jsonParam = param.apiJson || {};
    jsonParam.sCallback = 'uploadFinish';
    jsonParam.fCallback = 'uploadFinish';
    jsonParam = JSON.stringify(jsonParam);
    if (os.ios) {
      var src = 'goAddFile(' + jsonParam + ')';
      var iframe = document.createElement('iframe');
      iframe.setAttribute('src', src);
      iframe.setAttribute('style', 'display:none;');
      document.body.appendChild(iframe);
      setTimeout(function () {
        document.body.removeChild(iframe);
      }, 200);
    } else if (os.android) {
      accessoryfunc.goAddFile(jsonParam);
    } else {
      /* window['uploadFinish']({
       fId: '1234',
       originName: '我的文件',
       type: '.png',
       status: 200,
       code: 200
       });*/
      uploadFilePC({
        'url': JSON.parse(jsonParam).uploadUrl,
        onSend: function () {
          window['uploadFinish']({
            'isUpload': true
          });
        },
        success: function (retData) {
          loading.hide();
          if ('string' == typeof retData) {
            retData = JSON.parse(retData);
          }
          window['uploadFinish'](retData);
        },
        error: function () {
          loading.hide();
          mui.alert('上传失败！', '提示', function () {
          });
        }
      });
    }
  }

  /**
   * 19.下载附件
   */
  function crm_goDownload(param) {
    window['downLoadFinish'] = function (result) {
      if (typeof result == 'string') {
        result = JSON.parse(result);
      }
      param.callback(result);
      window['downLoadFinish'] = null;
    };
    var jsonParam = param.apiJson || {};
    jsonParam.sCallback = 'downLoadFinish';
    jsonParam = JSON.stringify(jsonParam);
    if (os.ios) {
      var src = 'goDownload(' + jsonParam + ')';
      var iframe = document.createElement('iframe');
      iframe.setAttribute('src', src);
      iframe.setAttribute('style', 'display:none;');
      document.body.appendChild(iframe);
      setTimeout(function () {
        document.body.removeChild(iframe);
      }, 200);
    } else if (os.android) {
      kndfunc.goDownload(jsonParam);
    } else {
      console.log('==========下载==========');
    }
  }

  /**
   * 28.时间控件
   * 参数 json
   * 'apiJson': {
   *    'format': '', //时间格式 如:'yyyy','yyyy-MM','HH:mm','yyyy-MM-dd HH:mm'
   *    'initDTime': '', //默认选中时间
   *    'minInterval': '' //间隔分钟数 , 能被60整除 如:5/10/20
   * }
   */
  function crm_setKndTime(param) {
    window['setKndTimeFinish'] = function (result) {
      if (typeof result == 'string') {
        result = JSON.parse(result);
      }
      param.callback(result);
      window['setKndTimeFinish'] = null;
    };
    var jsonParam = param.apiJson || {};
    jsonParam.sCallback = 'setKndTimeFinish';
    var endYear = new Date().getFullYear() + 10;
    if (!jsonParam.kndMinTime) {
      jsonParam.kndMinTime = '1900-01-01';
    }
    if (!jsonParam.kndMaxTime) {
      jsonParam.kndMaxTime = endYear + '-12-30';
    }
    jsonParam = JSON.stringify(jsonParam);
    jsonParam = JSON.parse(jsonParam);
    var dateType = 'date';
    if (jsonParam.format == 'yyyy') {
      dateType = 'year';
    } else if (jsonParam.format == 'yyyy-MM') {
      dateType = 'month';
    } else if (jsonParam.format == 'HH:mm') {
      dateType = 'time';
    } else if (jsonParam.format == 'yyyy-MM-dd HH:mm') {
      dateType = '';
    }
    var pickerParam = {
      'type': dateType,
      'value': jsonParam.initDTime,
      'beginYear': '1900',
      'endYear': endYear,
    }
    var picker = new mui.DtPicker(pickerParam);
    var self = this;
    picker.show(function (rs) {
      var dateResult = rs.text;
      if (jsonParam.format == 'yyyy') {
        dateResult = new Date(dateResult).getFullYear();
      }
      window['setKndTimeFinish']({
        'result': dateResult
      });
      picker.dispose();
    });
  }

  /**
   * 29.上传附件(.word,.exlx,.ppt)
   * 参数 json
   * 'apiJson': {
   *    'backType': '2', //1.表示只返回压缩图（不存本地）;2.表示只返回拍照生成的原图图片路径;3.表示返回压缩图和原图图片路径
   *    'wDivisor': '1024', //宽方向压缩的像素值
   *    'hDivisor': '780', //高方向压缩的像素值
   *    'uploadUrl': APIS.upload_file  //上传接口
   * }.
   * 'callback': function () {}
   * result: {'fId':'上传后附件ID', 'path':'上传后附件路径'}
   */
  function crm_uploadLibrary(param) {
    window['uploadFinish'] = function (result) {
      if (typeof result == 'string') {
        result = JSON.parse(result);
      }
      console.info(JSON.stringify(result) + '打印附件');
      if (result.isUpload) {
        loading.show('正在上传...');
        return;
      }
      loading.hide();
      if (result.status == 'cancel') {
        window['uploadFinish'] = null;
        return;
      }
      if (result.status == 1 || (result.code != 200 && param.apiJson.uploadUrl)) {
        mui.alert(result.msg || '上传失败，请重试！', '提示', function () {
        });
        window['uploadFinish'] = null;
        return;
      }
      if (!result.fileUrl && (os.ios || os.android)) {
        window['uploadFinish'] = null;
        return;
      }
      param.callback(result);
      window['uploadFinish'] = null;
    };
    var jsonParam = param.apiJson || {};
    jsonParam.sCallback = 'uploadFinish';
    jsonParam.fCallback = 'uploadFinish';
    jsonParam = JSON.stringify(jsonParam);
    uploadFilePC({
      'url': JSON.parse(jsonParam).uploadUrl,
      onSend: function () {
        window['uploadFinish']({
          'isUpload': true
        });
      },
      success: function (retData) {
        loading.hide();
        if ('string' == typeof retData) {
          retData = JSON.parse(retData);
        }
        window['uploadFinish'](retData);
      },
      error: function () {
        loading.hide();
        mui.alert('上传失败！', '提示', function () {
        });
      }
    });
  }


  /**非空判断**/
  function isNotNull(value) {
    if (value == undefined || value == null || value.length == 0) {
      return false;
    } else {
      return true;
    }
  }

  /**
   * 替换特殊字符
   * @param val
   */
  function replaceAllCh(val, type) {
    if (!val) {
      return '';
    }
    if (type) {
      /* val = val.replace(/x0a/g, '\n').replace(/@#$/g, '\\');*/
    } else {
      val = val.replace(/\\/g, '/');
    }
    return val;
  }

  /*
   * 加载中
   *
   * */
  var loading = {
    show: function (title) {
      var oDiv = document.getElementById('loading');
      oDiv.setAttribute('style', 'display: block;');
      var oTitle = document.getElementById('loading_title');
      oTitle.innerText = title;
      document.getElementById('loadingDelete').addEventListener('click', function () {
        loading.hide();
      });
    },
    hide: function () {
      try {
        var oDiv = document.getElementById('loading');
        oDiv.setAttribute('style', 'display: none;');
      } catch (e) {
      }
    }
  };
  /*
   * 加载中
   *
   * */


  /**
   *
   *  Base64 encode / decode
   *
   *  @author haitao.tu
   *  @date   2010-04-26
   *  @email  tuhaitao@foxmail.com
   *
   */
  function Base64() {

    // private property
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    // public method for encoding
    this.encode = function (input) {
      var output = '';
      var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
      var i = 0;
      input = _utf8_encode(input);
      while (i < input.length) {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        if (isNaN(chr2)) {
          enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
          enc4 = 64;
        }
        output = output +
          _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
          _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
      }
      return output;
    }

    // public method for decoding
    this.decode = function (input) {
      var output = '';
      var chr1, chr2, chr3;
      var enc1, enc2, enc3, enc4;
      var i = 0;
      input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
      while (i < input.length) {
        enc1 = _keyStr.indexOf(input.charAt(i++));
        enc2 = _keyStr.indexOf(input.charAt(i++));
        enc3 = _keyStr.indexOf(input.charAt(i++));
        enc4 = _keyStr.indexOf(input.charAt(i++));
        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;
        output = output + String.fromCharCode(chr1);
        if (enc3 != 64) {
          output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
          output = output + String.fromCharCode(chr3);
        }
      }
      output = _utf8_decode(output);
      return output;
    }

    // private method for UTF-8 encoding
    var _utf8_encode = function (string) {
      string = string.replace(/\r\n/g, '\n');
      var utftext = '';
      for (var n = 0; n < string.length; n++) {
        var c = string.charCodeAt(n);
        if (c < 128) {
          utftext += String.fromCharCode(c);
        } else if ((c > 127) && (c < 2048)) {
          utftext += String.fromCharCode((c >> 6) | 192);
          utftext += String.fromCharCode((c & 63) | 128);
        } else {
          utftext += String.fromCharCode((c >> 12) | 224);
          utftext += String.fromCharCode(((c >> 6) & 63) | 128);
          utftext += String.fromCharCode((c & 63) | 128);
        }

      }
      return utftext;
    }

    // private method for UTF-8 decoding
    var _utf8_decode = function (utftext) {
      var string = '';
      var i = 0;
      var c = 0;
      var c1 = 0;
      var c2 = 0;
      var c3 = 0;
      while (i < utftext.length) {
        c = utftext.charCodeAt(i);
        if (c < 128) {
          string += String.fromCharCode(c);
          i++;
        } else if ((c > 191) && (c < 224)) {
          c2 = utftext.charCodeAt(i + 1);
          string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
          i += 2;
        } else {
          c2 = utftext.charCodeAt(i + 1);
          c3 = utftext.charCodeAt(i + 2);
          string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
          i += 3;
        }
      }
      return string;
    }
  }



  var nativeApi = {
    initAjax: crm_ajax,
    goNative: crm_goNative,
    goPhoto: crm_goPhoto,
    goUpload: crm_uploadLibrary,
    fromImgLibrary: crm_fromImgLibrary,
    goAddFile: crm_openAddFile,
    goDownload: crm_goDownload,
    setKndTime: crm_setKndTime,
    replaceAllCh: replaceAllCh
  };

  module.exports = nativeApi;
  window.nativeApi = nativeApi;

});
